import React, {Component} from 'react';
import {
    StyleSheet, 
    View,
    Animated,
    Easing,
    Platform,
    Text,
    Dimensions,
    Modal,
    InteractionManager,
    TouchableOpacity,
    Image,
    SafeAreaView,
    DeviceEventEmitter,
} from 'react-native';

import RfidModule from '../component/Rfid';
import { RNCamera } from 'react-native-camera';
import BaseComponent from '../component/BaseComponent'
//import KeyEvent from 'react-native-keyevent';
const { width,height } = Dimensions.get('window');

import { getPixel, getScreenWidth, getScreenHeight } from '../common/common';
import DeviceInfo from 'react-native-device-info';
import {NavigationEvents} from 'react-navigation';

let that = {};

export default class QBarCodeScan extends BaseComponent {

    

    constructor(props) {
        super(props);
        this.state = {
            transCode:'', // 条码
            type: '', // 条码类型
            show: true,
            // animate: new Animated.Value(0), // 二维坐标{x:0,y:0}
            animate: new Animated.Value((width - 200) / 2,(height - 340) / 2),
            flashMode: RNCamera.Constants.FlashMode.torch,
            
        }
        that = this;
        // if(this.props.navigation.state.params.isRfid && this.props.navigation.state.params.isRfid === true && DeviceInfo.getDeviceId() === 'rk30sdk'){
        //     RfidModule.init(); // rfid设备初始化
        // }
    }

    back = () =>{
        this.props.navigation.goBack();
    }

    
    onBackClicked = () => {
       this.props.navigation.goBack();
       return true;
    }

    rfidReceived(rfids){
        //console.log(rfids);
        // console.log(rfids.length);
        // console.log(rfids && rfids.length > 0);
        if(rfids && rfids.length > 0){ 
            that.setState({
                flashMode: RNCamera.Constants.FlashMode.off,
            })       
            // if(rfids[0].length > 8){
            //     that.props.navigation.state.params.callBack(rfids[0].substring(rfids[0].length - 8));
            // }else{
            //     that.props.navigation.state.params.callBack(rfids[0]);
            // }
            that.props.navigation.state.params.callBack(rfids[0]);
            if(that.props.navigation.state.params.isGoBack){
                that.props.navigation.goBack();
            }  
        } 
        
    }

    rfidInit = () => {
        this.setState({
            flashMode: RNCamera.Constants.FlashMode.torch,
        })  
        if(this.props.navigation.state.params.isRfid && this.props.navigation.state.params.isRfid === true && DeviceInfo.getDeviceId() === 'rk30sdk'){
            if(RfidModule.getState() === 'uninit')
            {
                //console.log('rfid设备初始化' + RfidModule.getState());
                RfidModule.init(); // rfid设备初始化
                //console.log('rfid设备初始化完' + RfidModule.getState());
            }
            //console.log('注册按键事件');
            // KeyEvent.onKeyDownListener((keyEvent) => {
            //     console.log('按键='+keyEvent.keyCode)
            //     if(keyEvent.keyCode === 134){
            //         console.log('开启扫描')
            //         RfidModule.scan();
            //     }
            // });
            this.keyListener = DeviceEventEmitter.addListener('keydown', function(e) {
                //console.log('keycode: ' + e.which)
                if(e.which === 134){
                    //console.log('开启扫描111')
                    RfidModule.scan();
                }
                //console.log('keycode: ' + e.which)
            });
            this.rfidListener = DeviceEventEmitter.addListener('onRfidReveice', this.rfidReceived);
            //console.log("componentDidMountEnd");
        }
    }

    componentDidMount(){

    }

    // 动画开始
    startAnimation(){
        if(this.state.show){
            this.state.animate.setValue(0);
            Animated.timing(this.state.animate,{
                toValue: 1,   // 运动终止位置，比值
                duration: 2500,  // 动画时长
                easing: Easing.linear,  // 线性的渐变函数
                delay: 0.5,// 在一段时间之后开始动画（单位是毫秒），默认为0
            }).start(() => this.startAnimation())
        }
    }
    componentWillUnmount(){
        if(this.props.navigation.state.params.isRfid && this.props.navigation.state.params.isRfid === true && DeviceInfo.getDeviceId() === 'rk30sdk'){
            //console.log('destory');
            //KeyEvent.removeKeyDownListener();
            // if(RfidModule.getState() === 'init')
            // {
            //     RfidModule.destory();
            // }
            if(this.keyListener){
                this.keyListener.remove();
            }
            if(this.rfidListener){
                this.rfidListener.remove();
            }         
           
        }
        this.setState({
            show: false,
        })
    }

    barcodeReceived(e){
        // if(this.state.show){
        //     this.setState({
        //         transCode: e.data,
        //         type: e.type
        //     })
        // }
        this.setState({
            flashMode: RNCamera.Constants.FlashMode.off,
        })
        // if(!this.props.navigation.state.params.isCompleteData){ // 如果截取
        //     if(e.data.length > 8){
        //         that.props.navigation.state.params.callBack(e.data.substring(e.data.length - 8));
        //     }else{
        //         that.props.navigation.state.params.callBack(e.data);
        //     }  
        // }else{
        //     that.props.navigation.state.params.callBack(e.data);
        // };
        
        this.props.navigation.state.params.callBack(e.data);
        //console.log("退回" + this.props.navigation.state.params.isGoBack);
        if(this.props.navigation.state.params.isGoBack){
            this.props.navigation.goBack();
        }    
    }

    barcodeRecognized = ({barcodes}) => { 
        this.setState({
            flashMode: RNCamera.Constants.FlashMode.off,
        })  
        if(rfids[0].length > 8){
            that.props.navigation.state.params.callBack(barcodes[0].data.substring(barcodes[0].data.length - 8));
        }else{
            that.props.navigation.state.params.callBack(barcodes[0].data);
        }
        //this.props.navigation.state.params.callBack(barcodes[0].data);
        //console.log("退回" + this.props.navigation.state.params.isGoBack);
        if(this.props.navigation.state.params.isGoBack){
            this.props.navigation.goBack();
        }    
    };

   

    render() {
        return (
            <SafeAreaView style={styles.container}>
                <NavigationEvents onDidFocus={() => this.rfidInit() } />
                <View style={{flexDirection: 'row', backgroundColor: '#4A69DD', width: getScreenWidth()}}>
                    <View style={{ width: getPixel(55), justifyContent:'center', alignItems:'center'}}>

                    </View>
                    <View style={{ width: getScreenWidth() - getPixel(110), height: getPixel(40), }}>
                        <Text style={{height: getPixel(40),lineHeight: getPixel(40), textAlign:'center',fontSize: getPixel(16),color:'#FFF'}}>二维码扫描</Text>
                    </View>
                    <TouchableOpacity style={{width: getPixel(55), justifyContent:'center', alignItems:'center'}} onPress={ () => this.back() }>
                        <View style={{ width: getPixel(55), justifyContent:'center', alignItems:'center'}}>
                            <Image source={ require('../images/close.png')}  style={{ resizeMode: 'contain', width: getPixel(16), height: getPixel(16) }} />
                        </View>
                    </TouchableOpacity>
                </View>
                {
                    this.props.navigation.state.params.isHaveCamera === true ? 
                <RNCamera
                    onBarCodeRead={this.barcodeReceived.bind(this)}
                    onCameraReady={() => {
                        //console.log('ready')
                    }}
                    // onGoogleVisionBarcodesDetected={
                    //     this.barcodeRecognized
                    // }
                    // googleVisionBarcodeType={
                    //     RNCamera.Constants.GoogleVisionBarcodeDetection.BarcodeType.ALL
                    // }
                    ratio={'16:9'}
                    zoom={0}
                    captureAudio={false}
                    flashMode={this.state.flashMode}
                    autoFocus={RNCamera.Constants.AutoFocus.on}
                    androidCameraPermissionOptions={{
                        title: '系统需使用摄像头',
                        message: '需要您赋予摄像头使用权限',
                        buttonPositive: '确定',
                        buttonNegative: '取消',
                      }}
                    androidRecordAudioPermissionOptions={{
                        title: '系统需使用音频',
                        message: '需要您赋予音频使用权限',
                        buttonPositive: '确定',
                        buttonNegative: '取消',
                    }}
                    notAuthorizedView = {<View style={{height: getScreenHeight() - getPixel(150), justifyContent: 'center'}}><Text style={{textAlign: 'center'}}>未授权使用相机，请到手机设置开启本APP相机权限</Text></View>}
                    style={styles.camera}
                >
                    <View style={styles.box}>
                        <View style={styles.kuang}>
                            <Animated.View style={{
                                alignItems: 'center',
                                transform: [{
                                    // translateX: x轴移动
                                    // translateY: y轴移动
                                    translateY: this.state.animate.interpolate({
                                        inputRange: [0,1],
                                        outputRange: [0,200]
                                    })
                                }]
                            }}>
                                <Text style={{width:250,height:1,backgroundColor:'#00ff00'}}></Text>
                            </Animated.View>
                        </View>
                        <Text style={{ color:'#fff',marginTop: getPixel(10) }}>请将摄像头对准二维码进行扫描</Text>
                        {this.props.navigation.state.params.isRfid && this.props.navigation.state.params.isRfid === true && DeviceInfo.getDeviceId() === 'rk30sdk' ? 
                            <Text style={{ color:'#fff',marginTop: getPixel(5) }}>或使用扳机键进行RFID扫描</Text>:null
                        }
                    </View>
                    
                </RNCamera> :
                <View style={{width: getScreenWidth(), height: getScreenHeight(), justifyContent:'center', alignItems: 'center'}}>
                    <Text>设备无摄像头或设备异常，无法启动编码扫描</Text>
                    {this.props.navigation.state.params.isRfid && this.props.navigation.state.params.isRfid === true && DeviceInfo.getDeviceId() === 'rk30sdk' ? <Text>使用扳机键进行RFID扫描</Text> : null}
                </View>
            }
            </SafeAreaView>
        );
    }
}
 
const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    camera: {
        flex: 1,
    },
    box: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'rgba(0,0,0,0.6)',
    },
    kuang: {
        width: 260,
        height: 260,
        borderWidth: 1,
        borderColor: 'skyblue',
        backgroundColor: '#rgba(255,255,255,0.1)'
    },
    info: {
        width: width,
        height: 80,
        backgroundColor: '#fff',
        paddingLeft: 10,
        paddingBottom:5,
        justifyContent: 'space-around',
    }
});